<template>
  <div>
    <div class="output_sink">
      <TabPoint :pointList="pointList"> </TabPoint>
      <div id="pointBox" class="option_box">
        <el-form
          ref="formName"
          style="width: 100%"
          label-position="top"
          :model="form"
        >
          <div class="title" id="option">选项</div>
          <el-form-item
            label="名称"
            prop="name"
            :rules="[
              {
                required: true,
                message: '名称不能为空',
              },
            ]"
          >
            <el-input
              v-model="form.name"
              placeholder="请输入名称"
              size="small"
            ></el-input>
          </el-form-item>
          <AttrPagination
            @addAttribute="addAttribute"
            :attributeListPage="attributeListPage"
            @delAttribute="delAttribute"
          ></AttrPagination>
          <div id="shujuku">
            <div class="title">数据库</div>
            <el-form-item label="数据库类型" prop="type">
              <el-select
                size="small"
                v-model="form.type"
                placeholder="请输入或选择类型"
                @change="changeType"
              >
                <el-option
                  v-for="item in sources"
                  :key="item.name"
                  :value="item.name"
                  :label="item.name"
                ></el-option>
              </el-select>
            </el-form-item>
            <div v-if="form.type">
              <div v-if="form.sourceList.length !== 0">
                <el-form-item
                  style="display: flex"
                  label="类别"
                  prop="rdbmsType"
                  v-if="form.type == 'rdbms'"
                  :rules="[
                    {
                      required: form.sourceList.length !== 0,
                      message: '类别不能为空',
                    },
                  ]"
                >
                  <el-radio-group
                    style="margin-left: 10px"
                    v-model="form.rdbmsType"
                    @change="rdbmsChange"
                  >
                    <el-radio :label="0">内联配置</el-radio>
                    <el-radio :label="1">数据源</el-radio>
                    <el-radio :label="2">Jndi资源</el-radio>
                  </el-radio-group>
                </el-form-item>
                <div
                  v-for="(item, index) in form.sourceList"
                  :key="item.zhName + index"
                >
                  <!-- 表单验证这里必须是form的直接子属性  sourceList.' + index + '.defaultValue'-->
                  <!-- {{ item.type[0] }} -->
                  <el-form-item
                    :prop="'sourceList.' + index + '.defaultValue'"
                    :rules="[
                      {
                        required: true,
                        message: item.zhName + '不能为空',
                        trigger: 'blur',
                      },
                      {
                        validator(rule, value, callback) {
                          validatorForm(rule, value, callback, item);
                        },
                        trigger: 'blur',
                      },
                    ]"
                    :label="item.zhName"
                    v-if="item.optional === false"
                  >
                    <!-- item.type[0] -->
                    <el-radio-group
                      v-model="item.defaultValue"
                      v-if="item.type && item.type[0] === 'BOOL'"
                    >
                      <el-radio :label="true">是</el-radio>
                      <el-radio :label="false">否</el-radio>
                    </el-radio-group>
                    <el-input
                      :show-password="item.zhName.indexOf('密码') != -1"
                      v-else
                      size="small"
                      v-model="item.defaultValue"
                    ></el-input>
                  </el-form-item>
                  <el-form-item
                    v-else
                    :prop="'sourceList.' + index + '.defaultValue'"
                    :rules="[
                      {
                        required: false,
                        validator(rule, value, callback) {
                          validatorForm(rule, value, callback, item);
                        },
                        trigger: 'blur',
                      },
                    ]"
                  >
                    <el-checkbox slot="label" v-model="item.isCheck">{{
                      item.zhName
                    }}</el-checkbox>
                    <div v-if="item.isCheck">
                      <!-- 判断是否是BOOL类型的(bool显示单选组其他显示输入框) -->
                      <el-radio-group
                        v-model="item.defaultValue"
                        v-if="item.type && item.type[0] === 'BOOL'"
                      >
                        <el-radio :label="true">是</el-radio>
                        <el-radio :label="false">否</el-radio>
                      </el-radio-group>
                      <el-input
                        v-else
                        size="small"
                        v-model="item.defaultValue"
                      ></el-input>
                    </div>
                  </el-form-item>
                </div>
              </div>
              <el-form-item label="自定义选项">
                <div class="key_value_list">
                  <div style="margin-bottom: 10px" class="key_val_list">
                    <KeyValue
                      :propKey="'customOption.' + index + '.name'"
                      :propVal="'customOption.' + index + '.defaultValue'"
                      :rulesKey="[
                        {
                          required: true,
                          message: '键不能为空',
                          trigger: 'blur',
                        },
                        {
                          validator(rule, value, callback) {
                            validator(rule, value, callback);
                          },
                          trigger: 'blur',
                        },
                      ]"
                      :rulesVal="{
                        required: true,
                        message: '值不能为空',
                        trigger: 'blur',
                      }"
                      v-model="form.customOption[index]"
                      v-for="(item, index) in form.customOption"
                      :key="index"
                      @handDel="handDel(index, 'customOption')"
                    ></KeyValue>
                  </div>
                  <div class="key_v_btn" @click="handAddOption('customOption')">
                    <i
                      style="font-size: 12px; color: #666; margin-right: 10px"
                      class="el-icon-plus"
                    ></i>
                    <span> 添加 </span>
                  </div>
                </div>
              </el-form-item>
            </div>
          </div>
          <div id="zhushi">
            <div class="title" style="margin: 20px 0">注释</div>
            <el-checkbox
              class="pri_index_check"
              slot="label"
              v-model="isPrimaryKey"
              >@primaryKey</el-checkbox
            >
            <div class="key_value_list" v-if="isPrimaryKey">
              <div style="margin-bottom: 10px" class="key_val_list">
                <KeyValue
                  :isKey="false"
                  :propVal="'primaryKeyOption.' + index + '.defaultValue'"
                  :rulesVal="{
                    required: true,
                    message: '值不能为空',
                    trigger: 'blur',
                  }"
                  v-model="form.primaryKeyOption[index]"
                  v-for="(item, index) in form.primaryKeyOption"
                  :key="index"
                  @handDel="handDel(index, 'primaryKeyOption')"
                ></KeyValue>
              </div>
              <div class="key_v_btn" @click="handAddOption('primaryKeyOption')">
                <i
                  style="font-size: 12px; color: #666; margin-right: 10px"
                  class="el-icon-plus"
                ></i>
                <span> 添加 </span>
              </div>
            </div>
            <el-checkbox class="pri_index_check" slot="label" v-model="isIndex"
              >@index</el-checkbox
            >
            <div class="key_value_list" v-if="isIndex">
              <div style="margin-bottom: 10px" class="key_val_list">
                <KeyValue
                  :isKey="false"
                  :propVal="'indexOption.' + index + '.defaultValue'"
                  :rulesVal="{
                    required: true,
                    message: '值不能为空',
                    trigger: 'blur',
                  }"
                  v-model="form.indexOption[index]"
                  v-for="(item, index) in form.indexOption"
                  :key="index"
                  @handDel="handDel(index, 'indexOption')"
                ></KeyValue>
              </div>
              <div class="key_v_btn" @click="handAddOption('indexOption')">
                <i
                  style="font-size: 12px; color: #666; margin-right: 10px"
                  class="el-icon-plus"
                ></i>
                <span> 添加 </span>
              </div>
            </div>
            <Notes :items="treeItems" ref="notesRef"></Notes>
          </div>
        </el-form>
      </div>
    </div>
    <!-- 确认取消公共组件 -->
    <TopOperationButton @submit="submit" @handClose="handClose" />
  </div>
</template>

<script>
// mixins
import { optionForm } from "@/mixin/optionForm";
import { attrPage } from "@/mixin/attrPage";
import AttrPagination from "@/components/AttrPagination";
import Notes from "./component/Notes.vue";
import {
  getSourceMapList,
  setSourceMapList,
  setCheck,
  setOptions,
} from "@/views/edge/inputSourcePage/js/index";
import { generateId, reverseJson, empty } from "@/utils/index";
export default {
  mixins: [optionForm, attrPage],
  components: {
    AttrPagination,
    Notes,
  },

  props: {
    nodeDataRight: {
      type: Object,
      default: () => {},
    },
  },
  watch: {
    nodeDataRight: {
      handler: async function (newData, oldData) {
        // const metadata = await this.getMetadata();
        // metadata添加一个选中标识
        this.sources = setCheck(this.succSin.stores);
        if (newData) {
          let tempdata = JSON.parse(JSON.stringify(newData));
          console.log(tempdata, "节点", this.sources);
          this.dataId = tempdata.id;
          this.newData = tempdata;
          // 取后一个节点属性

          const {
            objectState,
            options,
            attributeList,
            store,
            annotationListObjects,
          } = tempdata;
          if (annotationListObjects) {
            this.setPriIndex(annotationListObjects);
            this.$nextTick(() => {
              // 自定义注解整理
              this.$refs.notesRef.treeItems = reverseJson(
                annotationListObjects,
                ["index", "primaryKey"]
              );
            });
          }
          this.form.name = tempdata.name || "";
          this.attributeListPage = attributeList || [];
          if (store) {
            const { options, type } = store;
            this.form.type = type || "";
            // 取出来原始的source数组
            const parameters =
              this.sources.find((item) => item.name == type)?.parameters || [];
            // 回显输入框组
            if (options) {
              // 区分出来自定义和原始数据
              const scuObj = setSourceMapList(options, parameters);
              const scuOptions = scuObj.options;
              if (type == "rdbms") {
                const newOption = setOptions(
                  options,
                  this.sources.find((item) => item.name == type)
                );
                this.form.sourceList = newOption.parameters;
                this.form.rdbmsType = newOption.id;
              } else {
                this.form.sourceList = scuOptions;
              }
              this.form.customOption = scuObj.customOption;
            }
          }
        }
      },
      immediate: true,
      deep: true,
    },
  },
  data() {
    return {
      dataId: "",
      form: {
        rdbmsType: 0,
        primaryKeyOption: [],
        indexOption: [],
        attTextarea: "",
        isKeyAtt: "",
        mapping: "",
        partition: false,
        options: [],
        sourceList: [],
        mapList: [],
        attributeList: [],
        type: "in-memory",
        isCorresponding: false,
        name: "",
      },
      treeItems: [],
      isPrimaryKey: false,
      isIndex: false,
    };
  },
  methods: {
    setPriIndex(data) {
      data.forEach((item) => {
        if (item.name == "index") {
          this.isIndex = true;
          this.form.indexOption = item.elements.map((m) => {
            return {
              defaultValue: m.value,
            };
          });
        }
        if (item.name == "primaryKey") {
          this.isPrimaryKey = true;
          this.form.primaryKeyOption = item.elements.map((m) => {
            return {
              defaultValue: m.value,
            };
          });
        }
      });
    },
    submit() {
      // const data = this.sourceList
      // 选项+自定义选项
      this.$refs["formName"].validate((valid) => {
        if (valid) {
          const sourceOption = getSourceMapList(this.form.sourceList);
          const customOption = getSourceMapList(this.form.customOption);

          if (
            this.$store.getters["siddhi/streamKeyIsRepear"]({
              id: this.dataId,
              val: this.form.name,
            })
          ) {
            this.$msg("流节点,表格节点,窗口节点名称不能重复!");
            return false;
          }
          if (this.attributeListPage.length == 0) {
            this.$msg("属性不能为空");
            return;
          }
          // 注解
          let notesList = this.$refs.notesRef.getNotes();
          const treeItems = this.$refs.notesRef.treeItems;

          if (this.isPrimaryKey) {
            notesList.annotationListObjects.unshift({
              elements: this.form.primaryKeyOption.map((item) => ({
                value: item.defaultValue,
              })),
              name: "primaryKey",
              annotations: [],
            });
            let primaryKeyOption = this.form.primaryKeyOption.map(
              (item) => `'${item.defaultValue}'`
            );
            notesList.annotationList.unshift(
              `@primaryKey(${primaryKeyOption.join(",")})`
            );
          }
          if (this.isIndex) {
            notesList.annotationListObjects.unshift({
              elements: this.form.indexOption.map((item) => ({
                value: item.defaultValue,
              })),
              annotations: [],
              name: "index",
            });
            let indexOption = this.form.indexOption.map(
              (item) => `'${item.defaultValue}'`
            );
            notesList.annotationList.unshift(`@index(${indexOption})`);
          }

          this.newData.store = {
            options: _.concat(sourceOption, customOption),
            type: this.form.type,
          };
          console.log(sourceOption, "=======", customOption);
          this.newData.type = this.form.type;
          this.newData.name = this.form.name;
          this.newData.attributeList = this.attributeListPage;

          notesList.annotationList = notesList.annotationList.filter(
            (item) => item != ""
          );
          Object.assign(this.newData, notesList);
          let returnData = {
            display: false,
            type: "tableList",
            objectState: this.nodeDataRight.objectState,
            nodeData: this.newData,
            treeItems,
            nodeDataRight: this.nodeDataRight,
          };
          console.log(notesList, "notesList");
          this.$emit("returnSource", returnData);
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.pri_index_check {
  margin: 10px 0;
  display: block;
}
.key_val_list {
  max-height: 600px;
  overflow-y: auto;
}
.output_sink {
  display: flex;
  /deep/ .el-tabs__header {
    height: 80vh;
  }
  /deep/ .attributeDrag {
    margin-top: 0;
  }
  .key_value_list {
    padding: 15px;
    /* padding-bottom: 0; */
    background: rgba(233, 233, 233, 0.3);
    .key_v_btn {
      height: 32px;
      width: 100%;
      border: 1px solid #999999;
      display: flex;
      align-items: center;
      justify-content: center;

      border-radius: 6px;
      cursor: pointer;
      span {
        font-size: 12px;
        color: #666;
      }
    }
  }
}
.option_box {
  height: 80vh;
  width: 100%;
  overflow-y: auto;
  padding-right: 10px;
  /deep/ .el-select {
    width: 100%;
  }
  /deep/ .el-form-item__label {
    padding-bottom: 0 !important;
    width: auto;
  }
  /deep/ .el-form-item {
    margin-bottom: 0;
    width: 100%;
  }
  /deep/ .el-radio {
    margin-right: 0;
  }

  .title {
    color: #333333;
    font-size: 16px;
    font-weight: bold;
  }
}
</style>
